package com.hospital.modules.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.common.enums.IsDeleteEnum;
import com.hospital.common.enums.MedicalImageTypeEnum;
import com.hospital.common.enums.SexEnum;
import com.hospital.common.exception.RRException;
import com.hospital.common.utils.DateUtils;
import com.hospital.common.utils.PageUtils;
import com.hospital.modules.sys.dao.SysPatientVisitRecordDao;
import com.hospital.modules.sys.entity.SysPatientVisitRecordEntity;
import com.hospital.modules.sys.entity.SysRecommenderEntity;
import com.hospital.modules.sys.entity.SysUserEntity;
import com.hospital.modules.sys.entity.dto.PatientVisitRecordExportDTO;
import com.hospital.modules.sys.entity.vo.SysPatientVisitQueryListVO;
import com.hospital.modules.sys.service.SysPatientVisitRecordService;
import com.hospital.modules.sys.service.SysRecommenderService;
import com.hospital.modules.sys.service.SysRoleService;
import com.hospital.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author geaofeng
 */
@Service("sysPatientVisitRecordService")
public class SysPatientVisitRecordServiceImpl extends ServiceImpl<SysPatientVisitRecordDao, SysPatientVisitRecordEntity> implements SysPatientVisitRecordService {

    @Autowired
    private SysPatientVisitRecordDao sysPatientVisitRecordDao;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRecommenderService sysRecommenderService;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public PageUtils queryPage(SysPatientVisitQueryListVO params, SysUserEntity sysUserEntity) {
        List<Long> roleIdList = sysRoleService.queryRoleIdListByUserId(sysUserEntity.getUserId());
        if (CollectionUtil.isEmpty(roleIdList)) {
            throw new RRException("此页面暂无查看权限");
        }

        QueryWrapper<SysPatientVisitRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", IsDeleteEnum.NO_DELETE.getValue());
        //如果不为空就查相关姓名的数据
        if (ObjectUtil.isNotEmpty(params.getPatientName())) {
            wrapper.like("patient_name", params.getPatientName());
        } else {
            //给查询一个默认值
            params.timeProcess();
        }
        //如果开始时间和结束时间不为空
        if (ObjectUtil.isNotEmpty(params.getStartTime()) && ObjectUtil.isNotEmpty(params.getEndTime())) {
            wrapper.between("clinic_time", params.getStartTime(), params.getEndTime());
        }
        wrapper.in("role_id", roleIdList);
        wrapper.orderByDesc("clinic_time");
        IPage<SysPatientVisitRecordEntity> page = sysPatientVisitRecordDao.selectPage(new Page<>(params.getPage(), params.getLimit()), wrapper);

        //获取结果
        List<SysPatientVisitRecordEntity> records = page.getRecords();


        if (CollectionUtil.isNotEmpty(records)) {

            records.stream().forEach(s -> {
                SysUserEntity userEntity = sysUserService.getById(s.getCreateBy());
                s.setCreateByName(userEntity == null ? "--" : userEntity.getUsername());
                s.setSexDesc(SexEnum.getEnumDescByValue(s.getSex()));
                String medicalImageType = s.getMedicalImageType();
                if (StringUtils.isNotEmpty(medicalImageType)) {
                    List<String> medicalImageTypeList = new ArrayList<>();
                    String[] split = medicalImageType.split(",");
                    Arrays.stream(split).forEach(v -> {
                        medicalImageTypeList.add(MedicalImageTypeEnum.getEnumDescByValue(Integer.valueOf(v)));
                    });
                    medicalImageType = medicalImageTypeList.stream().collect(Collectors.joining(","));
                    s.setMedicalImageType(medicalImageType);
                }

                if (s.getRecommenderId() > 0) {
                    SysRecommenderEntity sysRecommenderEntity = sysRecommenderService.getById(s.getRecommenderId());
                    s.setRecommender(sysRecommenderEntity == null ? "--" : sysRecommenderEntity.getRecommenderName());
                    s.setRecommenderMobile(sysRecommenderEntity == null ? "--" : sysRecommenderEntity.getRecommenderMobile());
                }
            });
        }
        return new PageUtils(page);
    }

    @Override
    public void insert(SysPatientVisitRecordEntity sysPatientVisitRecord, SysUserEntity sysUserEntity) {
        List<Long> roleIdList = sysRoleService.queryRoleIdListByUserId(sysUserEntity.getUserId());
        if (CollectionUtil.isEmpty(roleIdList)) {
            throw new RRException("此用户无添加数据的权限");
        }
        Date now = new Date();
        sysPatientVisitRecord.setCreateTime(now);
        sysPatientVisitRecord.setUpdateTime(now);
        Integer userId = sysUserEntity.getUserId().intValue();
        sysPatientVisitRecord.setCreateBy(userId);
        sysPatientVisitRecord.setUpdateBy(userId);
        //给员工角色中的其中一个，这里设计的添加患者的用户的角色不是跨医院的。
        sysPatientVisitRecord.setRoleId(roleIdList.get(0).intValue());
        sysPatientVisitRecord.setIsDelete(IsDeleteEnum.NO_DELETE.getValue());
        List<Integer> medicalImageTypeList = sysPatientVisitRecord.getMedicalImageTypeList();
        String medicalImageType = getMedicalImageType(medicalImageTypeList);
        sysPatientVisitRecord.setMedicalImageType(medicalImageType);

        sysPatientVisitRecordDao.insert(sysPatientVisitRecord);
    }

    @Override
    public void modify(SysPatientVisitRecordEntity sysPatientVisitRecord, SysUserEntity sysUserEntity) {
        sysPatientVisitRecord.setUpdateTime(new Date());
        sysPatientVisitRecord.setUpdateBy(sysUserEntity.getUserId().intValue());
        List<Integer> medicalImageTypeList = sysPatientVisitRecord.getMedicalImageTypeList();
        String medicalImageType = getMedicalImageType(medicalImageTypeList);
        sysPatientVisitRecord.setMedicalImageType(medicalImageType);
        sysPatientVisitRecordDao.updateById(sysPatientVisitRecord);
    }

    @Override
    public void delete(List<Integer> asList, SysUserEntity sysUserEntity) {

        List<SysPatientVisitRecordEntity> sysPatientVisitRecordEntities = sysPatientVisitRecordDao.selectBatchIds(asList);

        sysPatientVisitRecordEntities.stream().forEach(s -> {
            s.setIsDelete(IsDeleteEnum.IS_DELETE.getValue());
            s.setUpdateBy(sysUserEntity.getUserId().intValue());
            s.setUpdateTime(new Date());
        });
        this.updateBatchById(sysPatientVisitRecordEntities);
    }

    @Override
    public SysPatientVisitRecordEntity getInfoById(Integer id) {
        SysPatientVisitRecordEntity sysPatientVisitRecord = this.getById(id);
        if (ObjectUtil.isNotNull(sysPatientVisitRecord)) {
            String medicalImageType = sysPatientVisitRecord.getMedicalImageType();
            sysPatientVisitRecord.setMedicalImageTypeList(StringUtils.isEmpty(medicalImageType) ? Collections.EMPTY_LIST : Arrays.stream(medicalImageType.split(",")).map(Integer::parseInt).collect(Collectors.toList()));
            if (sysPatientVisitRecord.getRecommenderId() > 0) {
                SysRecommenderEntity sysRecommenderEntity = sysRecommenderService.getById(sysPatientVisitRecord.getRecommenderId());
                sysPatientVisitRecord.setRecommender(sysRecommenderEntity == null ? "--" : sysRecommenderEntity.getRecommenderName());
                sysPatientVisitRecord.setRecommenderMobile(sysRecommenderEntity == null ? "--" : sysRecommenderEntity.getRecommenderMobile());
            }
        }
        return sysPatientVisitRecord;
    }

    @Override
    public List<PatientVisitRecordExportDTO> export(SysPatientVisitQueryListVO params, SysUserEntity user) {
        List<Long> roleIdList = sysRoleService.queryRoleIdListByUserId(user.getUserId());
        if (CollectionUtil.isEmpty(roleIdList)) {
            throw new RRException("此页面暂无查看权限");
        }

        QueryWrapper<SysPatientVisitRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", IsDeleteEnum.NO_DELETE.getValue());
        //如果不为空就查相关姓名的数据
        if (ObjectUtil.isNotEmpty(params.getPatientName())) {
            wrapper.like("patient_name", params.getPatientName());
        } else {
            //给查询一个默认值
            params.timeProcess();
        }
        //如果开始时间和结束时间不为空
        if (ObjectUtil.isNotEmpty(params.getStartTime()) && ObjectUtil.isNotEmpty(params.getEndTime())) {
            wrapper.between("create_time", params.getStartTime(), params.getEndTime());
        }
        wrapper.in("role_id", roleIdList);
        wrapper.orderByDesc("create_time");
        List<SysPatientVisitRecordEntity> list = sysPatientVisitRecordDao.selectList(wrapper);
        List<PatientVisitRecordExportDTO> resp = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            resp = list.stream().map(s -> export(s)).collect(Collectors.toList());
        }
        return resp;
    }

    private PatientVisitRecordExportDTO export(SysPatientVisitRecordEntity entity) {
        PatientVisitRecordExportDTO target = new PatientVisitRecordExportDTO();
        target.setPatientName(entity.getPatientName());
        target.setAddress(entity.getAddress());
        target.setAge(entity.getAge());
        target.setClinicTime(DateUtils.format(entity.getClinicTime(), DateUtils.DATE_TIME_PATTERN));
        target.setCost(entity.getCost());
        SysUserEntity userEntity = sysUserService.getById(entity.getCreateBy());
        target.setCreateByName(userEntity == null ? "--" : userEntity.getUsername());
        target.setDiagnosis(entity.getDiagnosis());
        String medicalImageType = entity.getMedicalImageType();
        if (StringUtils.isNotEmpty(medicalImageType)) {
            medicalImageType = Arrays.stream(medicalImageType.split(",")).map(s -> MedicalImageTypeEnum.getEnumDescByValue(Integer.parseInt(s))).collect(Collectors.joining(","));
        }
        target.setMedicalImageType(medicalImageType);
        target.setSexDesc(SexEnum.getEnumDescByValue(entity.getSex()));
        Integer recommenderId = entity.getRecommenderId();
        SysRecommenderEntity sysRecommenderEntity = null;
        if (recommenderId > 0) {
            sysRecommenderEntity = sysRecommenderService.getById(recommenderId);
        }
        target.setRecommender(sysRecommenderEntity == null ? "--" : sysRecommenderEntity.getRecommenderName());
        target.setRecommenderMobile(sysRecommenderEntity == null ? "--" : sysRecommenderEntity.getRecommenderMobile());
        target.setVisitCount(entity.getVisitCount());
        target.setMobile(entity.getMobile());
        return target;
    }

    private String getMedicalImageType(List<Integer> medicalImageTypeList) {
        String medicalImageType = "";
        if (CollectionUtil.isNotEmpty(medicalImageTypeList)) {
            medicalImageType = medicalImageTypeList.stream().map(String::valueOf).collect(Collectors.joining(","));
            return medicalImageType;
        }
        return medicalImageType;
    }

}
